package com.dharma.BIO;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class BIOServer {

    private static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 20, 2,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(5));

    public static void bioServer()
    {
        // TODO 服务端处理客户端连接请求
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(3333);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 接收到客户端连接请求之后为每个客户端创建一个新的线程进行链路处理
        final ServerSocket finalServerSocket = serverSocket;
        Socket socket = null;
        try {
            socket = finalServerSocket.accept();
        } catch (IOException e) {
            e.printStackTrace();
        }
        final Socket finalSocket = socket;
        poolExecutor.execute(()->{
            try {
                int len;
                byte[] data = new byte[1024];
                InputStream inputStream = finalSocket.getInputStream();
                // 按字节流方式读取数据
                while ((len = inputStream.read(data)) != -1) {
                    System.out.println(new String(data, 0, len));
                }
            } catch (IOException e) {
                System.out.println("Error");
            }
        });
    }
}
